package com.jnzc.ocr.serv.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jnzc.ocr.common.utils.ValidateUtils;
import com.jnzc.ocr.dependencies.serv.mybatis.MybatisServiceImpl;
import com.jnzc.ocr.serv.system.consts.SysNoConsts;
import com.jnzc.ocr.serv.system.entity.SysNo;
import com.jnzc.ocr.serv.system.filter.SysNoFilter;
import com.jnzc.ocr.serv.system.mapper.SysNoMapper;
import com.jnzc.ocr.serv.system.service.SysNoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author zhangcm
 * @version 1.0, 2017-10-07
 */
@Service
public class SysNoServiceImpl extends MybatisServiceImpl<SysNoMapper, SysNo, SysNoFilter> implements SysNoService {

    @Override
    protected void fillEntityWrapper(EntityWrapper<SysNo> ew, SysNoFilter filter) {
        SysNo entity = new SysNo();
        entity.setCode(filter.getCode());
        ew.setEntity(entity);
    }

    @Override
    public SysNo find(String code) {
        ValidateUtils.notEmpty(code, 20, "key");
        SysNoFilter filter = new SysNoFilter();
        filter.setCode(code);
        SysNo obj = super.find(filter);
        if(null == obj){
            obj = new SysNo();
            obj.setCode(code);
            obj.setCount(0L);
            obj.setVersion(0L);
        }
        return obj;
    }

    @Override
    public Long getNext(String key) {
        SysNo no = find(key);
        Long next = no.getCount() + 1;
        no.setCount(next);
        this.save(no);
        return next;
    }

    @Override
    public String getNextShopNo(Long companyId) {
        ValidateUtils.isId(companyId);
        Long next = this.getNext(SysNoConsts.PREV_SHOP + companyId);
        return SysNoConsts.PREV_SHOP + StringUtils.leftPad(next.toString(), 3, "0");
    }

    @Override
    public String getNextUserNo(Long companyId) {
        ValidateUtils.isId(companyId);
        Long next = this.getNext(SysNoConsts.PREV_USER + companyId);
        return SysNoConsts.PREV_USER + StringUtils.leftPad(next.toString(), 3, "0");
    }

    @Override
    public String getNextMemberNo(Long companyId) {
        ValidateUtils.isId(companyId);
        Long next = this.getNext(SysNoConsts.PREV_MEMBER + companyId);
        return SysNoConsts.PREV_MEMBER + StringUtils.leftPad(next.toString(), 5, "0");
    }
}
